package com.example.bloodbankproject;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;

import com.example.bloodbankproject.bean.StateBean;
import com.example.bloodbankproject.global.GetResponse;
import com.example.bloodbankproject.global.Session;
/**
 * 
 * @author Chandra
 *
 */
public class DonorRegistration extends Activity implements OnItemSelectedListener {

	private EditText mDonarname, mAge, mPhno, mEmail, mAddress,  mZipcode;
	private RadioGroup mGender;
	private Spinner mBloodGroup,mState,mCity;
	private Button mSave;
	private TableLayout mTableLayout;
	private String donarName, age, phno, email, address, city, state, zipcode,gender, bloodgroup ,currentDateandTime;
	private ArrayList<StateBean> stateList = new ArrayList<StateBean>();
	private ArrayList<StateBean> citiesList = new ArrayList<StateBean>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.donarregistration);

		// setup the view(Edittext)

		mDonarname = (EditText) findViewById(R.id.name);
		mAge = (EditText) findViewById(R.id.age);
		mPhno = (EditText) findViewById(R.id.Phone);
		mEmail = (EditText) findViewById(R.id.emailid);
		mAddress = (EditText) findViewById(R.id.address);
		mCity = (Spinner) findViewById(R.id.city);
		mState = (Spinner) findViewById(R.id.state);
		mZipcode = (EditText) findViewById(R.id.zipcode);
		
		mTableLayout =(TableLayout) findViewById(R.id.tt_layout);
		
		
		GetStates getStates = new GetStates();
		getStates.execute("http://www.whizapi.com/api/util/ui/in/indian-states-list.htm?appkey=Tf3ZbMGA");

		// setup the view(Spinner)

		mBloodGroup = (Spinner) findViewById(R.id.bgroup);

		// setup the view(RadioGroup)

		mGender = (RadioGroup) findViewById(R.id.gender);

		// setup the view(Button)

		mSave = (Button) findViewById(R.id.bt_save);
		
		mState.setOnItemSelectedListener(this);
		mCity.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				StateBean  bean = citiesList.get(position);
				city= bean.getCity();				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		mSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				
				
				
				String[] deviceInfo = {ModulesActivity.apidString,ModulesActivity.deviceID}; 
				SendDeviceInfo connection = new SendDeviceInfo(deviceInfo);
				String url1 = Session.sInstanceUrl+"/services/data/v26.0/sobjects/Mobile_Device__c";
				connection.execute(url1);

				// getting data from EditText
				donarName = mDonarname.getText().toString();
				age = mAge.getText().toString();
				phno = mPhno.getText().toString();
				email = mEmail.getText().toString();
				address = mAddress.getText().toString();
				zipcode = mZipcode.getText().toString();
				/*state = mState.getSelectedItem().toString();
				city = mCity.getSelectedItem().toString();*/

				// getting data from spinner

				bloodgroup = mBloodGroup.getSelectedItem().toString();

				// getting data from RadioGroup

				if (mGender.getCheckedRadioButtonId() == R.id.male) {
					gender = "Male";
				} else {
					gender = "Female";
				}
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
				currentDateandTime = sdf.format(new Date());

				Log.i("NCS", "Total Values  :" + donarName + " : " + age + " :"
						+ phno + " : " + email + " : " + bloodgroup + " :"
						+ gender + " : " + address + " : " + city + " : "
						+ zipcode+":"+currentDateandTime);  
				;
				
				String[] data ={donarName,address,bloodgroup,city,age,email,phno,state,zipcode,gender,currentDateandTime};

				UrlConnection conn = new UrlConnection(data);
				String url = Session.sInstanceUrl
						+ "/services/data/v26.0/sobjects/DonorRegistration__c";
				conn.execute(url);
				
				
				
			}
		});

	}
	
	class UrlConnection extends AsyncTask<String, Void, String> {

		private HttpURLConnection http_url_conn;
		private String response;
		public String insertData[];
		public UrlConnection(String data[]){
			if(data!=null){
			insertData = data;
			}		
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {	
				URL w_Url = new URL(params[0]);
				http_url_conn = (HttpURLConnection) w_Url.openConnection();
				//Method
				http_url_conn.setRequestMethod("POST");
				
				// headers
				http_url_conn.setRequestProperty("Content-type", "application/json");
				http_url_conn.setRequestProperty("Authorization", "OAuth "+Session.sAccessToken);
				
				//Body
				JSONObject jsonParam = new JSONObject();
				jsonParam.put("Name",insertData[0]);
				jsonParam.put("Address__c",insertData[1]);
				jsonParam.put("BloodGroup__c",insertData[2]);
				jsonParam.put("City__c",insertData[3]);
				jsonParam.put("Donor_Age__c",insertData[4]);
				jsonParam.put("Email_ID__c",insertData[5]); 
				jsonParam.put("Phone_Number__c",insertData[6]);
				jsonParam.put("State__c",insertData[7]);
				jsonParam.put("ZipCode__c",insertData[8]);  
				jsonParam.put("Gender__c",insertData[9]);	
				jsonParam.put("Date__c",insertData[10]);
				
				Log.i("NCS","JsonResponse: "+jsonParam.toString());	
				          
				http_url_conn.setUseCaches(false);
				http_url_conn.setDoInput(true);
				http_url_conn.setDoOutput(true);

			      DataOutputStream wr = new DataOutputStream (
			    		  http_url_conn.getOutputStream ());
			      wr.writeBytes (jsonParam.toString());
			      wr.flush ();
			      wr.close ();
			      Log.i("RGT","Response code is  :"+http_url_conn.getResponseCode());
				  Log.i("RGT","Response Method is  :"+http_url_conn.getRequestMethod());
				  Log.i("RGT","Response Message is  :"+http_url_conn.getResponseMessage());
			      response =GetResponse.convert_To_String(http_url_conn.getInputStream());
			      return response;
			      } catch (Exception e) {
				
				Log.i("NCS","Exception 2 is  :"+e.getMessage());	
				
			}
			return null;
			
		}
		
		

		@Override
		protected void onPostExecute(String result) {
			
			if(result!=null){
				
				finish();
				
			}
			super.onPostExecute(result);
		}


	}
	
	class SendDeviceInfo extends AsyncTask<String, Void, String>{

		private HttpURLConnection http_url_conn;
		private String response;
		public String insertData[];
		public SendDeviceInfo(String data[]){
			if(data!=null){
			insertData = data;
			}		
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {	
				URL w_Url = new URL(params[0]);
				http_url_conn = (HttpURLConnection) w_Url.openConnection();
				http_url_conn.setRequestMethod("POST");
				http_url_conn.setRequestProperty("Content-type", "application/json");
				http_url_conn.setRequestProperty("Authorization", "OAuth "+Session.sAccessToken);
				JSONObject jsonParam = new JSONObject();
				jsonParam.put("Name",insertData[0]);
				jsonParam.put("MobileDeviceID__c",insertData[1]);
				Log.i("TPT","JsonResponse: "+jsonParam.toString());	
				http_url_conn.setUseCaches(false);
				http_url_conn.setDoInput(true);
				http_url_conn.setDoOutput(true);

			      DataOutputStream wr = new DataOutputStream (
			    		  http_url_conn.getOutputStream ());
			      wr.writeBytes (jsonParam.toString());
			      wr.flush ();
			      wr.close ();
			      Log.i("RGT","Response code is  :"+http_url_conn.getResponseCode());
				  Log.i("RGT","Response Method is  :"+http_url_conn.getRequestMethod());
				  Log.i("RGT","Response Message is  :"+http_url_conn.getResponseMessage());
			      response =GetResponse.convert_To_String(http_url_conn.getInputStream());
			      return response;
			      } catch (Exception e) {
				
				Log.i("NCS","Exception 2 is  :"+e.getMessage());	
				
			}
			return null;
			
		}
		
		

		@Override
		protected void onPostExecute(String result) {
			
			if(result!=null){
				
				
			}
			super.onPostExecute(result);
		}


	}
	
	class GetStates extends AsyncTask<String, Void, String>{


		private HttpURLConnection http_url_conn;
		private String response;
		public String insertData[];
		/*public GetStates(String data[]){
			if(data!=null){
			insertData = data;
			}		
		}*/
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {	
				URL w_Url = new URL(params[0]);
				http_url_conn = (HttpURLConnection) w_Url.openConnection();
				//Method
				http_url_conn.setRequestMethod("GET");
				
				// headers
				http_url_conn.setRequestProperty("Content-type", "application/json");

			    response =GetResponse.convert_To_String(http_url_conn.getInputStream());
			      return response;
			      } catch (Exception e) {
				
				Log.i("NCS","Exception 2 is  :"+e.getMessage());	
				
			}
			return null;
			
		}
		
		

		@Override
		protected void onPostExecute(String result) {
			
			if(result!=null){
			try{
				stateList.clear();
				JSONArray  _jArray = new JSONArray(result);
		 	   	int count = _jArray.length();
		 	   	com.google.gson.Gson gson = new com.google.gson.Gson();
		 	   	for(int i=0;i<count;i++){
		 	   		if(!_jArray.isNull(i)){
		 	   		StateBean bean = gson.fromJson(_jArray.getString(i), StateBean.class);
		 	   		stateList.add(bean);
		 	   		}
		 	   	
				}
		 	   	
		 	  
		 	   	
		 	   	refresh();
		 	   	
			}catch(Exception ex){
				 Log.i("NCS","Excep is :"+ex.getMessage());	
			}
			
		}
			super.onPostExecute(result);

	
	}
}
	
	public void refresh()
	{
		mTableLayout.setVisibility(View.VISIBLE);
		DisplayData data = new DisplayData(stateList);
		mState.setAdapter(data);
		
	}
	class DisplayData extends BaseAdapter {
		ArrayList<StateBean> list;

		public DisplayData(ArrayList<StateBean> sList) {
			
			list = sList;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public class ViewHolder{
			
			public TextView stateList;
			
			
		}

		@Override
		public View getView(int position, View v, ViewGroup arg2) {
			
			ViewHolder holder;
			
			if(v == null){
				
				LayoutInflater inflater = getLayoutInflater();
				v = inflater.inflate(R.layout.donordetailsdisplay, null);
				
				holder = new ViewHolder();
				
				holder.stateList = (TextView) v.findViewById(R.id.tv_donorname);
				
				v.setTag(holder);
				
			}else{
				
				holder = (ViewHolder) v.getTag();
			}
			
			
			
			StateBean bean = list.get(position);
			
			holder.stateList.setText(bean.getStateName());
			
			return v;
		}
		
		
		
	}
	
	
	class GetCities extends AsyncTask<String, Void, String>{


		private HttpURLConnection http_url_conn;
		private String response;
		public String insertData[];
		/*public GetStates(String data[]){
			if(data!=null){
			insertData = data;
			}		
		}*/
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			try {	
				URL w_Url = new URL(params[0]);
				http_url_conn = (HttpURLConnection) w_Url.openConnection();
				//Method
				http_url_conn.setRequestMethod("GET");
				
				// headers
				http_url_conn.setRequestProperty("Content-type", "application/json");

			    response =GetResponse.convert_To_String(http_url_conn.getInputStream());
			      return response;
			      } catch (Exception e) {
				
				Log.i("NCS","Exception 2 is  :"+e.getMessage());	
				
			}
			return null;
			
		}
		
		

		@Override
		protected void onPostExecute(String result) {
			
			if(result!=null){
			try{
				citiesList.clear();
				JSONArray  _jArray = new JSONArray(result);
		 	   	int count = _jArray.length();
		 	   	com.google.gson.Gson gson = new com.google.gson.Gson();
		 	   	for(int i=0;i<count;i++){
		 	   		if(!_jArray.isNull(i)){
		 	   		StateBean bean = gson.fromJson(_jArray.getString(i), StateBean.class);
		 	   		citiesList.add(bean);
		 	   		}
		 	   	
				}
		 	   	
		 	   
		 	   	
		 	   citiesRefresh();
		 	   	
			}catch(Exception ex){
				 Log.i("NCS","Excep is :"+ex.getMessage());	
			}
			
		}
			super.onPostExecute(result);

	
	}
}
	
	public void citiesRefresh(){
		
		CitiesDisplay data = new CitiesDisplay(citiesList);
		mCity.setAdapter(data);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View v, int position,
			long arg3) {
		
		StateBean  bean = stateList.get(position);
		state= bean.getStateName();
		int id = Integer.parseInt(bean.getId());
		
		GetCities url = new GetCities();
		url.execute("http://www.whizapi.com/api/util/ui/in/indian-city-by-state.htm?stateid="+id+"&appkey=Tf3ZbMGA");
		
	}
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
	
	class CitiesDisplay extends BaseAdapter{
		ArrayList<StateBean> list;

		public CitiesDisplay(ArrayList<StateBean> sList) {
			
			list = sList;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		public class ViewHolder{
			
			public TextView stateList;
			
			
		}

		@Override
		public View getView(int position, View v, ViewGroup arg2) {
			
			ViewHolder holder;
			
			if(v == null){
				
				LayoutInflater inflater = getLayoutInflater();
				v = inflater.inflate(R.layout.donordetailsdisplay, null);
				
				holder = new ViewHolder();
				
				holder.stateList = (TextView) v.findViewById(R.id.tv_donorname);
				
				v.setTag(holder);
				
			}else{
				
				holder = (ViewHolder) v.getTag();
			}
			
			
			
			StateBean bean = list.get(position);
			
			holder.stateList.setText(bean.getCity());
			
			return v;
		}
		
		
		
	}
	
}